package cn.tedu.controller;

import cn.tedu.pojo.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;

@RestController
@RequestMapping("student")
public class StudentController {

    //http://localhost:8080/student/save
    @RequestMapping("save")
    //1.注册驱动
    public String save(Student s) throws Exception{
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接（url user pwd）
        String url="jdbc:mysql://localhost:3306/cgb2108?characterEncoding=utf8";;
        String user = "root";
        String pwd = "";
        Connection c = DriverManager.getConnection(url,user,pwd);
        //3.获取传输器(用新传输器 否则SQL攻击)
        String sql="insert into tb_students values(null,?,?,?,?,?,?)";
       PreparedStatement ps = c.prepareStatement(sql);
//       ps.setString(1,s.getName());
//        ps.setInt(2,s.getId());
//        ps.setInt(3,s.getAge());
//
//        ps.setObject(4,s.getHobby());
//        ps.setObject(5,s.getEdu());
//        ps.setObject(6,s.getIntime());
       // ps.setString(1,s.getName());
        ps.setInt(2,s.getAge());
        ps.setInt(3,s.getId());
        //s.getHobby()获取到了数组,入库,数据库不认识数组,需要变成字符串才能入库,否则500
        ps.setObject(4, Arrays.toString( s.getHobby() ) );
        ps.setObject(5,s.getEdu());
        ps.setObject(6,s.getIntime());

        //s.getHobby()获取

        //4.执行SQL(insert)
        ps.executeQuery();
        //5.关闭资源
        ps.close();
        c.close();
        System.out.println("数据入库成功！");
        return "访问成功!"+s;
    }

}
